package service

import (
	"anban/models"
	"anban/utils"
	"github.com/astaxie/beego/orm"
	"net/url"
	"strconv"
	"time"
)

// 获取会员信息
func GetUserInfo(p map[string]interface{}) *models.User {
	o := orm.NewOrm()
	user := &models.User{}
	qs := o.QueryTable("User")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["openId"]; ok {
		qs = qs.Filter("open_id", p["openId"])
	}
	if _, ok := p["unionId"]; ok {
		qs = qs.Filter("union_id", p["unionId"])
	}
	if _, ok := p["familySn"]; ok {
		qs = qs.Filter("family_sn", p["familySn"])
	}
	qs.One(user)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if user.Id > 0 {
			if len(user.Phone) > 0 {
				user.PhoneShow = utils.FormatMobile(user.Phone)
			}
			user.IdentityShow = models.UserIdentity[user.Identity]
			user.SubscribeStatusShow = models.UserSubscribeStatus[user.SubscribeStatus]
			user.SubscribeTimeShow = user.SubscribeTime.Format("2006-01-02 15:04:05")
			user.UnsubscribeTimeShow = user.UnsubscribeTime.Format("2006-01-02 15:04:05")
			user.CreatedShow = user.Created.Format("2006-01-02 15:04:05")
			user.UpdatedShow = user.Updated.Format("2006-01-02 15:04:05")
		}
	}
	if _, ok := p["api"]; ok && p["api"].(bool) {
		if user.Id > 0 {
			if len(user.Phone) > 0 {
				user.PhoneShow = utils.FormatMobile(user.Phone)
			}

			p = map[string]interface{}{}
			p["status"] = 1
			p["familySn"] = user.FamilySn
			user.FamilyMemberNum, _ = GetUserList(p)

			p = map[string]interface{}{}
			p["status"] = 1
			p["familySn"] = user.FamilySn
			user.ChildrenMemberNum, _ = GetStudentList(p)
		}
	}
	return user
}

// 获取家庭编号
func GetUserFamilySn() string {
	familySn := utils.GetRandomString(32)
	p := map[string]interface{}{}
	p["familySn"] = familySn
	userInfo := GetUserInfo(p)
	for userInfo.Id > 0 {
		familySn = utils.GetRandomString(32)
		p = map[string]interface{}{}
		p["familySn"] = familySn
		userInfo = GetUserInfo(p)
	}
	return familySn
}

// 添加会员信息
func AddUser(input url.Values) (int64, error) {
	o := orm.NewOrm()
	user := &models.User{}
	inviteUser := &models.User{}
	if _, ok := input["invite_user_id"]; ok {
		inviteUser.Id = utils.Atoi64(input["invite_user_id"][0])
		o.Read(inviteUser)
	}
	user.InviteUser = inviteUser
	if _, ok := input["open_id"]; ok {
		user.OpenId = input["open_id"][0]
	}
	if _, ok := input["union_id"]; ok {
		user.UnionId = input["union_id"][0]
	}
	if _, ok := input["nick_name"]; ok {
		user.NickName = input["nick_name"][0]
	}
	if _, ok := input["head_img_url"]; ok {
		user.HeadImgUrl = input["head_img_url"][0]
	}
	if _, ok := input["status"]; ok {
		user.Status, _ = strconv.Atoi(input["status"][0])
	}
	if _, ok := input["is_main"]; ok {
		user.IsMain, _ = strconv.Atoi(input["is_main"][0])
	}
	if _, ok := input["subscribe_status"]; ok {
		user.SubscribeStatus, _ = strconv.Atoi(input["subscribe_status"][0])
	}
	if _, ok := input["subscribe_time"]; ok {
		loc, _ := time.LoadLocation("Local")
		theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", input["subscribe_time"][0], loc)
		user.SubscribeTime = theTime
	}
	return o.Insert(user)
}

// 修改会员信息
func EditUser(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	p["updated"] = time.Now().Format("2006-01-02 15:04:05")
	return o.QueryTable("User").Filter("id", input["id"][0]).Update(p)
}

// 获取会员列表
func GetUserList(p map[string]interface{}) (int64, []*models.User) {
	var userList []*models.User
	o := orm.NewOrm()
	qs := o.QueryTable("User")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["classId"]; ok {
		qs = qs.Filter("Students__Student__Class__Id", p["classId"])
	}
	if _, ok := p["teacherClassId"]; ok {
		qs = qs.Filter("Classes__Class__Id", p["teacherClassId"])
	}
	if _, ok := p["studentIds"]; ok && len(p["studentIds"].([]int64)) > 0 {
		qs = qs.Filter("Students__Student__Id__in", p["studentIds"])
	}
	if _, ok := p["familySn"]; ok {
		qs = qs.Filter("family_sn", p["familySn"])
	}
	if _, ok := p["realName"]; ok {
		qs = qs.Filter("real_name__contains", p["realName"])
	}
	if _, ok := p["idCard"]; ok {
		qs = qs.Filter("id_card__contains", p["idCard"])
	}
	if _, ok := p["phone"]; ok {
		qs = qs.Filter("phone__contains", p["phone"])
	}
	if _, ok := p["identity"]; ok {
		qs = qs.Filter("identity", p["identity"])
	}
	if _, ok := p["subscribeStatus"]; ok {
		qs = qs.Filter("subscribe_status", p["subscribeStatus"])
	}
	if _, ok := p["isMain"]; ok {
		qs = qs.Filter("is_main", p["isMain"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-id").Distinct().All(&userList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, user := range userList {
			user.StatusShow = models.UserStatus[user.Status]
			user.IdentityShow = models.UserIdentity[user.Identity]
			user.SubscribeStatusShow = models.UserSubscribeStatus[user.SubscribeStatus]
			user.SubscribeTimeShow = user.SubscribeTime.Format("2006-01-02 15:04:05")
			user.UnsubscribeTimeShow = user.UnsubscribeTime.Format("2006-01-02 15:04:05")
			user.CreatedShow = user.Created.Format("2006-01-02 15:04:05")
			user.UpdatedShow = user.Updated.Format("2006-01-02 15:04:05")
		}
	}
	if _, ok := p["api"]; ok && p["api"].(bool) {
		for _, user := range userList {
			if user.StudentRelation.Id > 0 {
				user.RelationName = user.StudentRelation.Name
			}
			if _, ok := p["apiWithCourse"]; ok && p["apiWithCourse"].(bool) {
				if _, ok := p["teacherClassId"]; ok {
					param := map[string]interface{}{}
					param["classId"] = p["teacherClassId"]
					param["relation"] = true
					param["userId"] = user.Id
					userClass := GetUserClassInfo(param)
					user.CourseName = userClass.Course.Name
				}
			}
		}
	}
	if _, ok := p["withCourse"]; ok && p["withCourse"].(bool) {
		if _, ok := p["teacherClassId"]; ok {
			for _, user := range userList {
				param := map[string]interface{}{}
				param["userId"] = user.Id
				param["classId"] = p["teacherClassId"]
				param["relation"] = true
				userClass := GetUserClassInfo(param)
				user.CourseName = userClass.Course.Name
			}
		}
	}
	return totalCount, userList
}